<template>
  <BasicLayout>
    <template #wrapper>
      <el-card class="box-card">
        <el-form ref="queryForm" :model="queryParams" :inline="true">
          <el-row>
            <el-col :span="5">
              <el-form-item prop="name" label="班级名称">
                <el-input
                  v-model="queryParams.name"
                  placeholder="请输入班级名称"
                  clearable
                  size="small"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item prop="head_master_name" label="班主任">
                <el-input
                  v-model="queryParams.head_master_name"
                  placeholder="请输入班主任名称"
                  clearable
                  size="small"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
            </el-col>
            <!-- <el-col :span="5">
              <el-form-item prop="dept_name" label="教学点">
                <el-input
                  v-model="queryParams.dept_name"
                  placeholder="请输入教学点"
                  clearable
                  size="small"
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
            </el-col> -->
            <el-col :span="5">
              <el-form-item label="班级分类" prop="class">
                <el-select v-model="queryParams.class" placeholder="请选择" clearable size="small">
                  <el-option v-for="dict in classOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item style="float:right">
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <el-row :gutter="20">
          <!-- <el-col :span="5" :xs="24">
            <div class="head-container">
              <el-tree
                ref="tree"
                :data="deptOptions"
                :props="defaultProps"
                :expand-on-click-node="false"
                :filter-node-method="filterNode"
                default-expand-all
                @node-click="handleNodeClick"
              />
            </div>
          </el-col>-->
          <el-col :span="24">
            <el-row :gutter="10" class="mb10" style="float:right">
              <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">删除
                </el-button>
              </el-col>
            </el-row>
            <el-table
              v-loading="loading"
              :data="dataList"
              border
              @selection-change="handleSelectionChange"
              @sort-change="handleSortChang"
            >
              <el-table-column type="selection" width="45" align="center" />
              <el-table-column label="班级名称" width="200" prop="name" :show-overflow-tooltip="true" />
              <el-table-column label="班级分类" prop="class" />
              <el-table-column label="班级类型" prop="class_type" width="80" />
              <!-- <el-table-column
                label="教学点"
                width="200"
                prop="teaching_point"
                :show-overflow-tooltip="true"
              >
                <template slot-scope="scope">
                  <span>{{ scope.row.dept? scope.row.dept.dept_name: '-' }}</span>
                </template>
              </el-table-column>-->
              <el-table-column label="班主任" prop="head_master_name" />
              <!-- <el-table-column label="教学点" prop="name" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  <span>{{ scope.row.dept ? scope.row.dept.name : '-' }}</span>
                </template>
              </el-table-column> -->
              <el-table-column label="班级人数" prop="count" />
              <el-table-column label="班级实际人数" prop="real_count" width="100" />
              <!-- <el-table-column label="大区经理" prop="regional_manager" />
              <el-table-column label="城市负责人" width="100" prop="city_leader" />
              <el-table-column label="招生负责人" width="100" prop="admissions_officer" />-->
              <el-table-column
                label="操作"
                width="280"
                fixed="right"
                align="center"
                class-name="small-padding fixed-width"
              >
                <template slot-scope="scope">
                  <el-button size="mini" type="text" icon="el-icon-user-solid">
                    <router-link :to="{ name: 'viewUsers', params: { id: scope.row.id } }">查看学员</router-link>
                  </el-button>
                  <el-button
                    size="mini"
                    :disabled="!multiple && single"
                    type="text"
                    icon="el-icon-user"
                    @click="handleUpdate(scope.row, 'add')"
                  >添加学员</el-button>
                  <el-button
                    size="mini"
                    :disabled="!multiple && single"
                    type="text"
                    icon="el-icon-edit"
                    @click="handleUpdate(scope.row, 'edit')"
                  >修改</el-button>
                  <el-button
                    :disabled="!multiple && single"
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDelete(scope.row)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <pagination
              v-show="total > 0"
              :total="total"
              :page.sync="queryParams.pageIndex"
              :limit.sync="queryParams.pageSize"
              @pagination="getList"
            />
          </el-col>
        </el-row>
      </el-card>
      <!-- 添加或修改参数配置对话框 -->
      <el-drawer
        ref="drawer"
        :size="clickType === 'edit' ? '30%' : '70%'"
        :title="clickType === 'edit' ? title + '班级' : '添加学员'"
        :visible.sync="open"
        direction="rtl"
        custom-class="demo-drawer"
      >
        <el-form v-if="clickType === 'edit'" ref="form" :model="form" :rules="rules" label-width="100px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="班级名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="班级类型" prop="class_type">
                <el-select
                  v-model="form.class_type"
                  style="width: 100%"
                  placeholder="请选择"
                  size="small"
                  @change="classChange"
                >
                  <el-option
                    v-for="dict in classTypeOptions"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <!-- <el-col v-if="showNumber" :span="24">
              <el-form-item label="所属教学点" prop="dept_id">
                <treeselect
                  v-model="form.dept_id"
                  :options="deptOptions"
                  :normalizer="normalizer"
                  :disable-branch-nodes="true"
                  :show-count="true"
                  placeholder="选择教学点"
                />
              </el-form-item>
            </el-col>-->
            <el-col :span="24">
              <el-form-item label="班级分类" prop="class">
                <el-select v-model="form.class" style="width: 100%" placeholder="请选择" size="small">
                  <el-option v-for="dict in classOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="班主任" prop="head_master">
                <el-select
                  v-model="form.head_master"
                  remote
                  filterable
                  placeholder="请选择教师"
                  :remote-method="remoteMethod"
                  :loading="selectload"
                  style="width: 100%"
                >
                  <el-option v-for="dict in headMasterList" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-if="showNumber" :span="24">
              <el-form-item label="班级人数" prop="count">
                <el-input-number
                  v-model="form.count"
                  controls-position="right"
                  placeholder="请输入班级人数"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <!-- <el-col :span="24">
              <el-form-item label="所属教学点" prop="dept_id">
                <el-select
                  v-model="form.dept_id"
                  remote
                  filterable
                  placeholder="请选择教学点"
                  :remote-method="remoteSchool"
                  :loading="selectload"
                  style="width: 100%"
                >
                  <el-option v-for="(item, index) in schoolList" :key="index" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col> -->
          </el-row>
        </el-form>
        <div v-else>
          <el-table v-loading="userLoading" :data="userList" highlight-current-row border @selection-change="addUser">
            <el-table-column type="selection" width="45" align="center" />
            <el-table-column label="序号" width="75" type="index" />
            <el-table-column label="名称" prop="name" :show-overflow-tooltip="true" />
            <el-table-column label="科别" prop="ke_bie" :show-overflow-tooltip="true" />
            <el-table-column label="教学点" prop="province" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <span>{{ scope.row.area_point ? scope.row.area_point.name : '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="就读院校" prop="province" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <span>{{ scope.row.college ? scope.row.college.colleges_name : '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="手机号码" prop="phone" />
          </el-table>
          <pagination
            v-show="total > 0"
            :total="userTotal"
            :page.sync="noClassParams.pageIndex"
            :limit.sync="noClassParams.pageSize"
            @pagination="noClassStudents"
          />
        </div>
        <div style="position: fixed;bottom: 10px;right: 30px">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-drawer>
    </template>
  </BasicLayout>
</template>

<script>
import { importTemplate, userList } from '@/api/admin/sys-user'
import {
  listGrade,
  addGrade,
  delGrade,
  updateGrade,
  getNoClassStudents,
  addStudent
} from '@/api/admin/sys-grade'
import { getSchoolList } from '@/api/admin/sys-academy'
// import { treeselect } from "@/api/admin/sys-dept";
// import Treeselect from "@riophae/vue-treeselect";
// import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: 'SysGradeManage',
  // components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      userLoading: true,
      // 选中数组
      ids: [],
      studentIds: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 用户表格数据
      dataList: [],
      userList: [],
      userTotal: 0,
      // 弹出层标题
      title: '',
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 城市负责人
      cityLeaderList: [],
      showNumber: false,
      // 大区经理
      regionalManagerList: [],
      // 招生负责人
      admissionsOfficer: [],
      headMasterList: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      classOptions: [
        {
          label: '文科',
          value: '文科'
        },
        {
          label: '理科',
          value: '理科'
        }
      ],
      classTypeOptions: [
        {
          label: '网课',
          value: '网课'
        },
        {
          label: '面授',
          value: '面授'
        }
      ],
      // 查询参数
      queryParams: {
        pageIndex: 1,
        pageSize: 10,
        name: undefined,
        head_master_name: undefined,
        class: undefined,
        dept_name: undefined
      },
      noClassParams: {
        pageIndex: 1,
        pageSize: 10
      },
      // 表单校验
      rules: {
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        head_master: [
          { required: true, message: '请选择班主任', trigger: 'blur' }
        ],
        class: [{ required: true, message: '请选择班级分类', trigger: 'blur' }],
        class_type: [
          { required: true, message: '类型不能为空', trigger: 'blur' }
        ],
        // dept_id: [
        //   { required: true, message: '教学点不能为空', trigger: 'blur' }
        // ],
        count: [{ required: true, message: '人数不能为空', trigger: 'blur' }]
      },
      schoolParams: {
        pageIndex: 1,
        pageSize: 1000,
        name: undefined
      },
      schoolList: [],
      selectload: false,
      clickType: '',
      classId: null
    }
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getList()
    // this.getTreeselect();
    // 获取班主任
    this.fetchListUser()
    // // 招生负责人
    // this.fetchListUser(1);
    // // 大区经理
    // this.fetchListUser(2);
    // // 城市负责人
    // this.fetchListUser(3);

    this.getSchoolList()
  },
  methods: {
    classChange(e) {
      this.showNumber = e === '面授'
    },
    // 用户数据
    fetchListUser(id = 5) {
      userList().then(response => {
        const list =
          response.data?.map(item => ({
            label: item.nick_name,
            value: item.user_id
          })) ?? []
        switch (id) {
          case 1:
            this.admissionsOfficer = list
            break
          case 2:
            this.regionalManagerList = list
            break
          case 3:
            this.cityLeaderList = list
            break
          default:
            this.headMasterList = list
            break
        }
      })
    },
    getList() {
      this.loading = true
      listGrade(this.queryParams).then(response => {
        this.dataList = response.data.list
        this.total = response.data.count
        this.loading = false
      })
    },
    getSchoolList() {
      getSchoolList(this.schoolParams).then(res => {
        this.schoolList = res?.data?.list || []
        this.selectload = false
      })
    },
    /** 查询部门下拉树结构 */
    // getTreeselect() {
    //   treeselect().then(response => {
    //     this.deptOptions = response.data;
    //   });
    // },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = '/' + data.id + '/'
      this.getList()
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.label,
        children: node.children
      }
    },
    /** 排序回调函数 */
    handleSortChang(column, prop, order) {
      prop = column.prop
      order = column.order
      if (this.order !== '' && this.order !== prop + 'Order') {
        this.queryParams[this.order] = undefined
      }
      if (order === 'descending') {
        this.queryParams[prop + 'Order'] = 'desc'
        this.order = prop + 'Order'
      } else if (order === 'ascending') {
        this.queryParams[prop + 'Order'] = 'asc'
        this.order = prop + 'Order'
      } else {
        this.queryParams[prop + 'Order'] = undefined
      }
      this.getList()
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {}
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageIndex = 1
      this.queryParams.deptId = null
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      // this.queryParams.deptId = ''
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    addUser(selection) {
      this.studentIds = selection.map(item => item.id)
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加'
      this.clickType = 'edit'
    },
    noClassStudents() {
      this.userLoading = true
      getNoClassStudents(this.noClassParams).then(response => {
        this.userList = response.data.list
        this.userTotal = response.data.count
        this.userLoading = false
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row, type) {
      this.clickType = type
      this.open = true
      this.classId = row.id
      if (type === 'edit') {
        this.reset()
        this.form = {
          id: row.id,
          name: row.name,
          class_type: row.class_type,
          class: row.class,
          count: row.count,
          head_master: row.head_master,
          regional_manager_id: row.regional_manager_id || null,
          city_leader_id: row.city_leader_id || null,
          admissions_officer_id: row.admissions_officer_id || null,
          dept_id: row?.dept_id
        }
        this.showNumber = row.class_type === '面授'
        this.title = '修改'
      } else {
        this.noClassStudents()
      }
    },
    getNames(list = [], id) {
      const info = list.find(item => item.value === id) ?? {}
      return info.label ?? ''
    },
    /** 提交按钮 */
    submitForm: function() {
      if (this.clickType === 'edit') {
        this.$refs['form'].validate(valid => {
          if (valid) {
            this.form.admissions_officer = this.getNames(
              this.admissionsOfficer,
              this.form.admissions_officer_id
            )
            this.form.head_master_name = this.getNames(
              this.headMasterList,
              this.form.head_master
            )
            this.form.regional_manager = this.getNames(
              this.regionalManagerList,
              this.form.regional_manager_id
            )
            this.form.city_leader = this.getNames(
              this.cityLeaderList,
              this.form.city_leader_id
            )
            if (this.form.id !== undefined) {
              updateGrade(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess(response.msg)
                  this.open = false
                  this.getList()
                  this.form = {}
                } else {
                  this.msgError(response.msg)
                }
              })
              return
            }
            this.form.teaching_point =
              this.form.teaching_point ?? this.deptOptions?.[0].id
            addGrade(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess(response.msg)
                this.open = false
                this.getList()
                this.form = {}
              } else {
                this.msgError(response.msg)
              }
            })
          }
        })
      } else {
        addStudent({
          class_id: this.classId,
          id: this.studentIds
        }).then(response => {
          if (response.code === 200) {
            this.msgSuccess(response.msg)
            this.open = false
            this.getList()
          } else {
            this.msgError(response.msg)
          }
        })
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = (row.id && [row.id]) || this.ids
      this.$confirm('是否确认删除该数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(function() {
          return delGrade({ ids })
        })
        .then(response => {
          if (response.code === 200) {
            this.msgSuccess(response.msg)
            this.getList()
          } else {
            this.msgError(response.msg)
          }
        })
        .catch(function() { })
    },
    remoteMethod(query) {
      if (query !== '') {
        this.selectload = true
        userList({ nick_name: query }).then(res => {
          this.headMasterList =
            res.data?.map(item => ({
              label: item.nick_name,
              value: item.user_id
            })) ?? []
          this.selectload = false
        })
      } else {
        this.headMasterList = []
      }
    },
    remoteSchool(data) {
      if (data !== '') {
        this.selectload = true
        this.schoolParams.name = data
        this.getSchoolList()
      } else {
        this.schoolList = []
      }
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = '用户导入'
      this.upload.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.download(response.msg)
      })
    }
  }
}
</script>

<style>
.el-tag+.el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

/* .el-form-item__content{
  width: 162px;
} */
</style>
